// 此目录就为vuex数据目录
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
// 插件方式插入到Vue类中
Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    count: 1,
    users: null
  },
  // getters,它是就是计算属性,它也是缓存
  getters: {
    users(state) {
      return (
        (state.users &&
          state.users.map(item => ({
            ...item,
            age: item.age > 20 ? '不说' : item.age
          }))) || []
      )
    }
  },
  // mutation它是用来完成对于state数据的修改,同步操作
  mutations: {
    setCount(state, payload) {
      state.count += payload
    },
    setUsers(state, data) {
      state.users = data
    }
  },
  // 异步操作所用
  actions: {
    async fetchUserAction(store, payload) {
      // 异步操作
      let ret = await axios.get('/api/users')
      // console.log(store, ret.data)
      // 调用commit让mutation来修改state
      store.commit('setUsers', ret.data.data)
    }
  }
})

export default store
